package demo.aqs;


import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;

/**
 * @author : feixiang.li
 * @since : 2025-09-16 10:03
 */
public class MyLock {

    AtomicInteger state = new AtomicInteger(0);
    Thread owner;

    AtomicReference<Node> head = new AtomicReference<>(new Node());
    AtomicReference<Node> tail = new AtomicReference<>(head.get());

    class Node {
        Node next;
        Node prev;
        Thread thread;
    }

    void lock() {
        // 如果我们抢到锁
        if (state.compareAndSet(0, 1)) {
            System.out.println("线程：" + Thread.currentThread().getName() + " 直接抢锁成功");
            owner = Thread.currentThread();
            return;
        }

        // 下面是没有抢到锁的逻辑。将自己安全的放在队列尾部
        Node current = new Node();
        current.thread = Thread.currentThread();
        while (true) {
            Node currentTail = tail.get();
            if (tail.compareAndSet(currentTail, current)) {
                System.out.println("线程：" + current.thread.getName() + " 加入队列");
                currentTail.next = current;
                current.prev = currentTail;
                break;
            }
        }
        while (true) {
            // 先确认队列头是不是自己，是则抢锁成功。
            if (current.prev == head.get() && state.compareAndSet(0, 1)) {
                owner = Thread.currentThread();
                head.set(current);
                current.prev.next = null;
                current.prev = null;
                return;
            }
            // 先确认了是否有前面的节点来 唤醒自己
            LockSupport.park();
        }
    }

    void unlock() {
        if (owner != Thread.currentThread()) {
            throw new RuntimeException("不能解锁");
        }
        Node headNode = head.get();
        Node nextNode = headNode.next;
        state.set(0);
        if (nextNode != null) {
            System.out.println("唤醒下一个线程:{}" + nextNode.thread.getName());
            LockSupport.unpark(nextNode.thread);
        }
    }
}

